package com.example.feidaolumanager.pages.ui.machine

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.idesign.cui.statefullayout.StatefulStatus
import com.example.feidaolumanager.api.RetrofitClient
import com.example.feidaolumanager.pojo.MachineItem
import com.example.feidaolumanager.pojo.PmAvgInfo
import com.example.feidaolumanager.pojo.ResponseDTO
import com.example.feidaolumanager.pojo.User
import com.example.feidaolumanager.pojo.VO.MachineVO
import com.example.feidaolumanager.pojo.machineCategory.MachineCategoriesItem
import kotlinx.coroutines.launch

class MachinesViewModel : ViewModel() {


    val status = MutableLiveData(StatefulStatus.Loading)

    val machineList: MutableState<List<MachineItem>> = mutableStateOf(listOf())
    val workMachineCount = mutableIntStateOf(0)
    val noWorkMachineCount = mutableIntStateOf(0)
    private val demolitionMachineCount = mutableIntStateOf(0)

    var tokenExpire = MutableLiveData(false)

    private var machineCategories = mutableStateListOf<MachineCategoriesItem>()

    var level1MachineCategoryName = mutableStateListOf<String>()
    var level2MachineCategoryName = mutableStateListOf<MutableList<String>>()
    var level3MachineCategoryName = mutableStateListOf<MutableList<MutableList<String>>>()

    var addMachineResult = MutableLiveData<ResponseDTO<String>?>(null)
    var updateMachineResult = MutableLiveData<ResponseDTO<String>?>(null)
    var deleteMachineResult = MutableLiveData<ResponseDTO<String>?>(null)

    val areaPm25ValueAvgList = mutableStateListOf<PmAvgInfo>()

    fun addMachine(machineVO: MachineVO) {
        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.machineService.addMachine(machineVO)
            } catch (e: Exception) {
                when (e) {
                    is java.io.InterruptedIOException -> {
                        status.value = StatefulStatus.NetError
                    }

                    else -> {}
                }
                return@launch
            }
            addMachineResult.value = responseDTO
        }
    }

    fun deleteMachine(machineId: Int) {
        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.machineService.deleteMachine(machineId)
            } catch (e: Exception) {
                when (e) {
                    is java.io.InterruptedIOException -> {
                        status.value = StatefulStatus.NetError
                    }

                    else -> {}
                }
                return@launch
            }
            deleteMachineResult.value = responseDTO
        }
    }

    fun updateMachine(machineVO: MachineItem) {
        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.machineService.updateMachine(machineVO)
            } catch (e: Exception) {
                when (e) {
                    is java.io.InterruptedIOException -> {
                        status.value = StatefulStatus.NetError
                    }

                    else -> {}
                }
                return@launch
            }
            updateMachineResult.value = responseDTO
        }
    }


    fun getMachines(user: User, selKey: Int? = null, selLevel: Int? = null) {
        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.machineService.getMachines(
                    id = user.ss_id,
                    selKey = selKey,
                    selLevel = selLevel,
                    userAccount = user.account,
                    level = user.level.toString()
                )
            } catch (e: Exception) {
                when (e) {
                    is java.io.InterruptedIOException -> {
                        status.value = StatefulStatus.NetError
                    }

                    else -> {}
                }
                return@launch
            }

            if (responseDTO.code == 1) {
                machineList.value = responseDTO.data?.records ?: listOf()

                workMachineCount.intValue = 0
                noWorkMachineCount.intValue = 0
                demolitionMachineCount.intValue = 0
                machineList.value.forEach {
                    when (it.status) {
                        1 -> workMachineCount.intValue++
                        0 -> noWorkMachineCount.intValue++
                        2, 3 -> demolitionMachineCount.intValue++
                    }
                }
            } else {
                tokenExpire.value = true
            }


        }
    }

    /**
     * 获取所有的机械类型
     */
    fun getMachineCategories() {

        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.machineService.getMachineCategories()
            } catch (e: Exception) {
                return@launch
            }


            if (responseDTO.code == 1) {
                machineCategories.addAll(responseDTO.data!!)


                level1MachineCategoryName.clear()
                level2MachineCategoryName.clear()
                level3MachineCategoryName.clear()

                machineCategories.forEach { level1MachineCategory ->
                    level1MachineCategoryName.add(level1MachineCategory.category_name)

                    level2MachineCategoryName.add(arrayListOf())
                    level3MachineCategoryName.add(arrayListOf())

                    if (level1MachineCategory.children.isEmpty()) {
                        // 如果没有第二层，第二层和第三层也要补充一个空数组展位
                        level2MachineCategoryName.last().add("")
                        level3MachineCategoryName.last().add(arrayListOf(""))
                    } else {
                        level1MachineCategory.children.forEach {

                            level2MachineCategoryName.last().add(it.category_name)
                            level3MachineCategoryName.last().add(arrayListOf())

                            if (it.children.isEmpty()) {
                                level3MachineCategoryName.last().last().add("")
                            } else {
                                it.children.forEach { _ ->
                                    level3MachineCategoryName.last().last().add("")
                                }
                            }

                        }
                    }

                }
            } else {
                if (responseDTO.msg == "401") {
                    // 登录过期，跳转到登录页
                    tokenExpire.value = true
                }
            }
        }
    }

    fun getPmAvg(user: User?) {
        viewModelScope.launch {
            val responseDTO = try {
                RetrofitClient.machineService.getAvg(
                    userId = user?.ss_id.toString(),
                    userAccount = user?.account.toString(),
                    level = user?.level.toString()
                )
            } catch (e: Exception) {
                when (e) {
                    is java.io.InterruptedIOException -> {
                        status.value = StatefulStatus.NetError
                    }

                    else -> {}
                }
                return@launch
            }


            responseDTO.data?.let {
                areaPm25ValueAvgList.clear()
                areaPm25ValueAvgList.addAll(it)
            }
        }
    }

}